(function(angular) {
	'use strict';
	angular.module('fs.waf').factory('ppfSiteProfileService', ppfSiteProfileService);
	ppfSiteProfileService.$inject = [ '$q', '$timeout', 'loggerFactory', 'ajaxServiceFactory', 'modalService', 'gridService', 'arithService', '$filter' ];
	function ppfSiteProfileService($q, $timeout, loggerFactory, ajaxServiceFactory, modalService, gridService, arithService, $filter) {
		var log = loggerFactory.getLogger("ppfSiteProfileService"), ajaxService = ajaxServiceFactory.buildAjaxService({
			getProdSubtypeOptions : {
				url : 'do/cda/dataList/ppfArodSubtypeOptions',
				method : 'get'
			},
			getLayoutConfigByProdType: {
				url : 'do/cda/ppfSiteProfile/layout',
				method : 'post'					
			},
		});
		
		
		function initGeneral($scope, ctrl, updateProcessFlag) {
			var defer = $q.defer();
			ajaxService.getProdSubtypeOptions().then(function(response) {
				ctrl.prodSubtypeOptions = response.data;
				defer.resolve();
			});
			
			ctrl.prodSubtypeChanged = function(newValue) {
				if (ctrl.ppfSiteProfile.prodSubtype && ctrl.ppfSiteProfile.prodSubtype != ctrl.ppfSiteProfile.oldProdSubtype) {
					ctrl.ppfSiteProfile.oldProdSubtype = ctrl.ppfSiteProfile.prodSubtype;
					for (var i = 0; i < ctrl.prodSubtypeOptions.length; i++) {
						var _prodSubtype = ctrl.prodSubtypeOptions[i];
						if (_prodSubtype.value == ctrl.ppfSiteProfile.prodSubtype) {
							resetProgramByProdSubtypeExtProperty(ctrl, _prodSubtype);
							break;
						}
					}
					//
					var params = {};
					params.action = ctrl.action;
					params.prodSubtype = ctrl.ppfSiteProfile.prodSubtypeExtProperty.prodSubtypeName;
					ajaxService.getLayoutConfigByProdType(params).then(function(response) {
						var tmp = angular.copy(ctrl.ppfSiteProfile);
						// 1. change layout
						ctrl.layoutConfig = response.data;
						// reset model after change layout
						$timeout(function(){
							ctrl.ppfSiteProfile = tmp;
							// reset cust prop data
							ctrl.resetCustProperties();
						});
					});
				}
			};
			
			return defer.promise;
		}
		
		function initLayoutConfigAndModel ($scope, ctrl, initPpfSiteProfile, action) {
			var defer3 = $q.defer();
			if (initPpfSiteProfile.prodSubtype) {
				initPpfSiteProfile.oldProdSubtype = initPpfSiteProfile.prodSubtype;
				for (var i = 0; i < ctrl.prodSubtypeOptions.length; i++) {
					var _prodSubtype = ctrl.prodSubtypeOptions[i];
					if (_prodSubtype.value == initPpfSiteProfile.prodSubtype) {
						resetProgramByProdSubtypeExtProperty(ctrl, _prodSubtype, initPpfSiteProfile);
						break;
					}
				}
				//
				var params = {};
				params.action = action;
				params.prodSubtype = initPpfSiteProfile.prodSubtypeExtProperty.prodSubtypeName;
				ajaxService.getLayoutConfigByProdType(params).then(function(response) {
					// 1. change layout
					ctrl.layoutConfig = response.data;
					$timeout(function() {
						// reset model after change layout
						ctrl.ppfSiteProfile = initPpfSiteProfile;
						// reset cust prop data
						ctrl.resetCustProperties();
						defer3.resolve();
					});
				});
			}
			// create also get layout again for get all dynaparm by ppfSiteProfile
			// this will get '*'
			else if (action == 'create') {
				var params = {};
				params.action = action;
				params.prodSubtype = '';
				ajaxService.getLayoutConfigByProdType(params).then(function(response) {
					// 1. change layout
					ctrl.layoutConfig = response.data;
					// reset model after change layout
					$timeout(function(){
						ctrl.ppfSiteProfile = initPpfSiteProfile;
						// reset cust prop data
						ctrl.resetCustProperties();
						defer3.resolve();
					});
				});
			}
			return defer3.promise;
		};
		
		function resetProgramByProdSubtypeExtProperty (ctrl , _prodSubtype, initPpfSiteProfile) {
			var tmpPpfSiteProfile;
			if (initPpfSiteProfile) {
				tmpPpfSiteProfile = initPpfSiteProfile;
			} else {
				tmpPpfSiteProfile = ctrl.ppfSiteProfile;
			}
			
			tmpPpfSiteProfile.prodSubtypeExtProperty = _prodSubtype.extProperty;
		}
		function initCustProp(initLayoutConfig, $scope, ctrl, updateProcessFlag) {
			//
			if(ctrl.validatorConfig) initLayoutConfig.formConfigs.customerProfile.tableConfigs.tableSele.validatorConfig = ctrl.validatorConfig.customerProfile;
			ctrl.selectedPropertyInnerGridOptions = gridService.createInnerGridOptions($scope, initLayoutConfig.formConfigs.customerProfile.tableConfigs.tableSele, customerProfileSeleRowSelectionChanged);
			ctrl.selectedPropertyInnerGridOptions.data = 'vm.ppfSiteProfile.ppfSiteProfileProps';//dynamicParams
			ctrl.selectedPropertyInnerGridOptions.verifyData = 'vm.ppfSiteProfileOld.ppfSiteProfileProps';
			ctrl.selectedPropertyInnerGridOptions.multiSelect = true;
			function customerProfileSeleRowSelectionChanged(eventRow, selectedRows) {
				ctrl.selectedCustPropSeleRows = selectedRows;
			}
			
			if (initLayoutConfig.formConfigs.customerProfile.tableConfigs.tableAvai) {
				ctrl.hasAvailablePropertyInnerGrid = 'Y';//edit page is 'Y', view page is 'N'
				ctrl.availablePropertyInnerGridOptions = gridService.createInnerGridOptions($scope, initLayoutConfig.formConfigs.customerProfile.tableConfigs.tableAvai, customerProfileAvaiRowSelectionChanged);
				ctrl.availablePropertyInnerGridOptions.data = 'vm.availableProperties';
				ctrl.availablePropertyInnerGridOptions.multiSelect = true;
				function customerProfileAvaiRowSelectionChanged(eventRow, selectedRows) {
					ctrl.selectedCustPropAvaiRows = selectedRows;
				}
			}
			
			//
			ctrl.addPpfSiteProfileProp = function(){
				if (!ctrl.selectedCustPropAvaiRows || ctrl.selectedCustPropAvaiRows.length == 0) {
					modalService.openErrorDialogs({
						messages : [ 'title.dialogs.info.norecsel' ]
					});
					return;
				}
				if (!ctrl.ppfSiteProfile.dynamicParams) {								
					ctrl.ppfSiteProfile.dynamicParams = {};
				}
				angular.forEach(ctrl.selectedCustPropAvaiRows, function(selectedCustPropAvai, key) {
					angular.forEach(ctrl.availableProperties, function(availableProperty, index) {
						if (availableProperty.$$hashKey == selectedCustPropAvai.$$hashKey) {
							ctrl.availableProperties.splice(index, 1);
							// some new add not in site.dynamicParams, so need put it in
							if (!ctrl.ppfSiteProfile.dynamicParams[availableProperty.name] || !ctrl.ppfSiteProfile.dynamicParams[availableProperty.name].value) {
								ctrl.ppfSiteProfile.dynamicParams[availableProperty.name] = availableProperty;
								angular.merge(availableProperty, availableProperty.dynamicParameter);
							}
							// change 
							var corProf = angular.copy(availableProperty);
							corProf.dynamicParams = {};
							corProf.dynamicParams[availableProperty.name] = availableProperty;
							ctrl.ppfSiteProfile.ppfSiteProfileProps.push(corProf);
						}
					});
				});
				
				ctrl.selectedCustPropAvaiRows = [];
				
			};

			ctrl.removePpfSiteProfileProp = function(){
				if (!ctrl.selectedCustPropSeleRows || ctrl.selectedCustPropSeleRows.length == 0) {
					modalService.openErrorDialogs({
						messages : [ 'title.dialogs.info.norecsel' ]
					});
					return;
				}
				angular.forEach(ctrl.selectedCustPropSeleRows, function(selectedParam, key) {
					angular.forEach(ctrl.ppfSiteProfile.ppfSiteProfileProps, function(ppfSiteProfileProp, index) {
						if (ppfSiteProfileProp.$$hashKey == selectedParam.$$hashKey) {
							// clear for delete, 
							delete ctrl.ppfSiteProfile.dynamicParams[ppfSiteProfileProp.name];
							
							ctrl.ppfSiteProfile.ppfSiteProfileProps.splice(index, 1);
							ctrl.availableProperties.push(ppfSiteProfileProp);
						}
					});
				});
				
				// if not do, after of remove item's items value would be clear
				var orgProps = angular.copy(ctrl.ppfSiteProfile.ppfSiteProfileProps);
				ctrl.ppfSiteProfile.ppfSiteProfileProps = [];
				$timeout(function(){
					ctrl.ppfSiteProfile.ppfSiteProfileProps = orgProps;
				});
				
				ctrl.selectedCustPropSeleRows = [];
			};
			
			ctrl.resetCustProperties = function () {
				resetSelectedProperties();
				resetAvailableProperties();
			};
			
			function resetSelectedProperties () {
				ctrl.ppfSiteProfile.ppfSiteProfileProps = [];
				//ctrl.ppfSiteProfile.ppfSiteProfileProps
				var dynamicParams = ctrl.ppfSiteProfile.dynamicParams;
				if (dynamicParams) {
					angular.forEach(dynamicParams, function(dynamicParam, key) {
						// some new add prop or exist prop, then remove, also commit to server but value is empty, so need add '&& dynamicParam.value' to check
						if (dynamicParam.category == 'PPFCUSTOMERPROFILE' && dynamicParam.value) {
							ctrl.ppfSiteProfile.ppfSiteProfileProps.push(dynamicParam);
						}
					});
				}
				
				//
				if (ctrl.ppfSiteProfileOld) {
					if (!ctrl.ppfSiteProfileOld.ppfSiteProfileProps) {								
						ctrl.ppfSiteProfileOld.ppfSiteProfileProps = [];
					}
					//ctrl.ppfSiteProfile.ppfSiteProfileProps
					var oldDynamicParams = ctrl.ppfSiteProfileOld.dynamicParams;
					if (oldDynamicParams) {
						angular.forEach(oldDynamicParams, function(dynamicParam, key) {
							// some new add prop or exist prop, then remove, also commit to server but value is empty, so need add '&& dynamicParam.value' to check
							if (dynamicParam.category == 'PPFCUSTOMERPROFILE' && dynamicParam.value) {
								// change, build some dynaparm define
								var corProf = angular.copy(dynamicParam);
								// need dynamicParameter.name and dynamicParameter.dispKey
								corProf.dynamicParameter = angular.copy(dynamicParam);
//								// value is such as dynamicParams.CDA_DYNAPARM2.value
//								corProf.dynamicParams = {};
//								corProf.dynamicParams[dynamicParam.name] = dynamicParam;
//								corProf.model = 'dynamicParams.'+ dynamicParam.name +'.value';
								ctrl.ppfSiteProfileOld.ppfSiteProfileProps.push(corProf);
							}
						});
					}
				}
			}
			
			function resetAvailableProperties () {
				// change layoutConfig, get subCata 'CUSTOMERPROFILE'
				var custProfAvaiProps = [];
				var gridConfigs = ctrl.layoutConfig.formConfigs.customerProfile.gridConfigs;
				if (gridConfigs) {
					angular.forEach(gridConfigs, function(gridConfig, key) {
						if (gridConfig.dynamicParameter && gridConfig.dynamicParameter.category == 'PPFCUSTOMERPROFILE') {
							//
							var customerProfile = angular.copy(gridConfig);
							var hasInSele = false;
							if (ctrl.ppfSiteProfile.ppfSiteProfileProps && ctrl.ppfSiteProfile.ppfSiteProfileProps.length > 0) {
								for (var i = 0; i < ctrl.ppfSiteProfile.ppfSiteProfileProps.length; i++) {
									var ppfSiteProfileProp = ctrl.ppfSiteProfile.ppfSiteProfileProps[i];
									if ($filter("encode")(ppfSiteProfileProp.id) == $filter("encode")(customerProfile.dynamicParameter.id)) {
										hasInSele = true;
										delete ppfSiteProfileProp.label;
										// change 
										var corProf = customerProfile;
										corProf.dynamicParams = {};
										corProf.dynamicParams[ppfSiteProfileProp.name] = ppfSiteProfileProp;
										// only for update verify
										corProf.primaryKey = ppfSiteProfileProp.primaryKey;
										corProf.value = ppfSiteProfileProp.value;
										ctrl.ppfSiteProfile.ppfSiteProfileProps[i] = corProf;
										break;
									}
								}
							}
							if (!hasInSele)
								custProfAvaiProps.push(customerProfile);
							//this will in tab cust Profile, not show other place
							gridConfig.show = false;
						}
					});
				}
				// some has value but not has layout dynaparm, need clear
				if (ctrl.ppfSiteProfile.ppfSiteProfileProps && ctrl.ppfSiteProfile.ppfSiteProfileProps.length > 0) {
					for (var i = ctrl.ppfSiteProfile.ppfSiteProfileProps.length - 1; i >= 0 ; i--) {
						var ppfSiteProfileProp = ctrl.ppfSiteProfile.ppfSiteProfileProps[i];
						if (!ppfSiteProfileProp.dynamicParams) {
							ctrl.ppfSiteProfile.ppfSiteProfileProps.splice(i, 1);
						}
					}
				}
				ctrl.availableProperties = custProfAvaiProps;
				
				sortDynamicParamters(ctrl.ppfSiteProfile.ppfSiteProfileProps);
				sortDynamicParamters(ctrl.availableProperties);
			};
			
			function sortDynamicParamters(serviceDymamicParamters){
				if(!serviceDymamicParamters){
					return;
				}
				serviceDymamicParamters.sort(function(p1, p2){
					return arithService.gt(p1.dynamicParameter.dispOrder, p2.dynamicParameter.dispOrder) ? 1 : -1;
				});
			}
		}
		
		
		return {
			initGeneral : initGeneral,
			initLayoutConfigAndModel : initLayoutConfigAndModel,
			initCustProp : initCustProp
		};
	}
})(angular);
